<?php

namespace App\Service\playlet;
use App\Model\AppletCoupon;
use App\Model\AppletCouponPromotionActivity;
use App\Model\Applet;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;
use App\Service\queue\DyCouponService;
use Hyperf\Di\Annotation\Inject;
class AppletCouponPromotionActivityService extends CommicService
{
    const cacheDuration = 60 * 15;

    #[Inject]
    private DyCouponService $dyCouponService;

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = AppletCouponPromotionActivity::query()
            ->leftJoin('applet','applet.id','=','applet_coupon_promotion_activity.applet_id')
            ->select(['applet.name as applet_name','applet_coupon_promotion_activity.id','activity_id','error_msg','activity_name','coupon_meta_id','applet_coupon_promotion_activity.status','valid_begin_time','valid_end_time','short_title','applet_coupon_promotion_activity.created_at','applet_coupon_promotion_activity.updated_at']);

        if ($keyword) {
            $query->orWhere([['activity_name', 'like', '%'.$keyword.'%']]);
        }
        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        return $models;
    }

    public function createOrUpdate(Array $postData,$is_update=false,AppletCouponPromotionActivity $AppletCouponPromotionActivityInfo = null){


        //小程序券参数
        $applet_id = $postData['applet_id'];
        $applet_coupon_id = $postData['applet_coupon_id'];
        $activity_name = $postData['activity_name'];
        $receive_limit = $postData['receive_limit'] ?? 1;
        $valid_time = $postData['valid_time'];
        $valid_begin_time = $valid_time[0];
        $valid_end_time = $valid_time[1];
        $action_trigger = $postData['action_trigger']  ?? 0;
        $high_value_content = $postData['high_value_content'];
        $jump_text = $postData['jump_text'];
        $short_title = $postData['short_title'];
        $recent_bubble_text = $postData['recent_bubble_text'];

        //查询小程序券是否存在
        $appletData = Applet::query()->where(['id' => $applet_id])->select(['id','app_id'])->first();
        if(empty($appletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '小程序不存在');
        }
        //查询投放平台是否存在
        $appletCouponData = AppletCoupon::query()->where(['id' => $applet_coupon_id])->select(['id','coupon_meta_id'])->first();
        if(empty($appletCouponData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '小程序券不存在');
        }

        if (strtotime($valid_begin_time) >= strtotime($valid_end_time)) {
            return $this->response(SystemCode::SYSTEM_ERROR, '券开始时间不能大于结束时间');
        }

        Db::beginTransaction();
        try {

            $model = !empty($AppletCouponPromotionActivityInfo)? $AppletCouponPromotionActivityInfo : new AppletCouponPromotionActivity();
            if(!$is_update){
                $model->applet_id = $applet_id;

                $model->applet_coupon_id = $applet_coupon_id;
                $model->action_trigger = $action_trigger;
                $model->coupon_meta_id = $appletCouponData->coupon_meta_id;
            }
            $model->receive_limit = $receive_limit;
            $model->activity_name = $activity_name;
            $model->valid_begin_time = $valid_begin_time;
            $model->valid_end_time = $valid_end_time;
            $model->high_value_content = $high_value_content;
            $model->jump_text = $jump_text;
            $model->short_title = $short_title;
            $model->recent_bubble_text = $recent_bubble_text;

            if($model->save()){

                if($is_update){

                    $updateResult = $this->dyCouponService->updatePromotionActivity($model,$appletData->app_id);
                    if($updateResult['err_no'] != 0){
                        Db::rollBack();
                        return $this->response(SystemCode::SYSTEM_ERROR, $updateResult['err_msg']);
                    }

                }else{
                    $createResult = $this->dyCouponService->createPromotionActivity($model,$appletData->app_id,$appletCouponData->coupon_meta_id);
                    if($createResult['err_no'] != 0){
                        Db::rollBack();
                        return $this->response(SystemCode::SYSTEM_ERROR, $createResult['err_msg']);
                    }
                    $activity_id = $createResult['data']['activity_id'];
                    $model->activity_id = $activity_id;
                    $model->save();
                }
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
            }

        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }

    }
    public function delete($appletCouponPromotionActivityInfo){
        Db::beginTransaction();
        try {
//            $deleteResult['err_no'] = 0;
            $deleteResult = $this->dyCouponService->updateActivityStatus($appletCouponPromotionActivityInfo,6);
            if($deleteResult['err_no'] != 0) {
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR, $deleteResult['err_msg']);
            }
            $appletCouponPromotionActivityInfo->deleted_at = date('Y-m-d H:i:s');
            $appletCouponPromotionActivityInfo->save();
            Db::commit();
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }
    public function updateStatus($AppletCouponPromotionActivityInfo,$params){
        Db::beginTransaction();
        try {

            $status = $params['status'];
            $updateResult = $this->dyCouponService->updateActivityStatus($AppletCouponPromotionActivityInfo,$status);
//            $updateResult['err_no'] = 0;
            if($updateResult['err_no'] != 0) {
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR, $updateResult['err_msg']);
            }
            $AppletCouponPromotionActivityInfo->status = $status;
            $AppletCouponPromotionActivityInfo->save();
            Db::commit();
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }
}